/*
 * Copyright (c) 2007 jNetX.
 * http://www.jnetx.com
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * jNetX. You shall not disclose such Confidential Information and
 * shall use it only in accordance with the terms of the license
 * agreement you entered into with jNetX.
 *
 * $Id$
 */
package com.jnetx.javax.sip.address;

import com.jnetx.javax.sip.util.ByteArrayUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.text.ParseException;

/**
 * @author <a href="mailto:dparhonin@jnetx.ru">Dmitry Parhonin</a>
 * @version $Revision$
 */
class TelURLParser extends URIParserBase<TelURLImpl> {
    private static final Log logger = LogFactory.getLog(TelURLParser.class);

    protected Log getLogger() {
        return logger;
    }

    TelURLParser() {
    }

    public TelURLImpl parse(byte[] data, int start, int end, TelURLImpl uriObject) throws ParseException {
        if (uriObject == null) uriObject = new TelURLImpl();
        final int schemaEnd = ByteArrayUtil.firstOccurence(data, ':', start, end);
        if (schemaEnd == -1)
            fail("The URI scheme cannot be recognized!", start);
        final String scheme = new String(data, start, schemaEnd - start);
        if (scheme.equals(""))
            fail("Malformed URI!", start);
        if (!scheme.equals("tel"))
            fail("Unknown URI scheme: " + scheme, start);
        final int parameterStart = ByteArrayUtil.firstOccurence(data, ';', schemaEnd + 1, end);
        int phoneNumberStart = schemaEnd + 1;
        final int phoneNumberEnd = parameterStart != -1 ? parameterStart : end;
//        String phoneNumber = new String(data, phoneNumberStart, );
        if (phoneNumberEnd == phoneNumberStart)
            fail("The TelURL doesn't have any phone number info!", phoneNumberStart);
        if (data[phoneNumberStart] == '+') {
            uriObject.setGlobal(true);
            phoneNumberStart++;
        } else
            uriObject.setGlobal(false);
        uriObject.setPhoneNumber(new String(data, phoneNumberStart, phoneNumberEnd-phoneNumberStart));
        if (parameterStart != -1)
            parseParameters(data, parameterStart + 1, end, uriObject);
        if (!uriObject.isGlobal() && uriObject.getPhoneContext() == null)
            fail("The local phone number must have phone context defined!", parameterStart);
        return uriObject;
    }
}
/*
 * $Log$
 */